package StudyCode.summary.mycollection;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class IsCollectionOrArrayByString {
	public static void main(String[] argv) {
		String type = "www.tah1986.com";
		System.out.println(type + "是不是集合(Collection)或数组?");
		System.out.println(isArrayOrCollection(type));
	}

	public static boolean isArrayOrCollection(String type) {
		return isCollection(type) || isArray(type);
	}

	public static boolean isCollection(String type) {
		return isList(type) || isSet(type);
	}

	public static boolean isArray(String type) {
		return type != null
				&& (type.startsWith("[") && type.length() >= 2
				&& getArrayType(type) != null || type
				.endsWith("[]"));
	}

	public static boolean isList(String type) {
		return "java.util.List".equals(type);
	}

	public static boolean isSet(String type) {
		return "java.util.Set".equals(type);
	}

	public static Class getArrayType(String type) {
		if (type.endsWith("[]")) {
			try {
				return Class.forName(type.substring(0, type.length() - 2));
			} catch (ClassNotFoundException e) {
				throw new RuntimeException("Wrong array type");
			}
		}
		switch (type.substring(0, 2)) {
			case "[Z":
				return boolean.class;
			case "[B":
				return byte.class;
			case "[S":
				return short.class;
			case "[I":
				return int.class;
			case "[J":
				return long.class;
			case "[F":
				return float.class;
			case "[D":
				return double.class;
			case "[C":
				return char.class;
			case "[L":
				return Object.class;
		}
		throw new RuntimeException("Wrong array type");
	}
}
